import { createRouter, createWebHistory } from 'vue-router'
import { useCookies } from '@vueuse/integrations/useCookies';
import { ElNotification } from 'element-plus'

import { verifyToken } from '@/api/user';
const cookie = useCookies()
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'welcome',
      component: () => import('@/views/Welcome.vue'),
      meta: {
        requiresAuth: false, // 不需要权限校验
      },
    },
    
    {
      path: '/home',
      name: 'home',
      component: () => import('@/views/Home.vue'),
      meta: {
        requiresAuth: true, // 需要权限校验
      },
      redirect: '/home/upload',
      children: [
        {
          path: 'upload',
          component: () => import('@/views/Upload.vue'),
        },
        {
          path: 'select',
          component: () => import('@/views/Select.vue'),
        },
        {
          path: 'userSelect',
          component: () => import('@/views/UserSelect.vue'),
        },
        {
          path: 'about',
          component: () => import('@/views/About.vue'),
        },
      ],
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/Register.vue'),
      meta: {
        requiresAuth: false, // 不需要权限校验
      },
    },
  ],
})
router.beforeEach((to, from, next) => {
  console.log(`准备: 从 ${from.fullPath} 导航到 ${to.fullPath}`);
  
  // 判断是否登录
  const token = cookie.get("user-token");
  
  verifyToken(token)
    .then(res => {
      console.log("token验证成功，已登录状态");
      // 用户已登录
      handleNavigation(to, from, next, true);
    })
    .catch(err => {
      console.log("token验证失败，未登录状态");
      // 用户未登录
      handleNavigation(to, from, next, false);
    });
});

// 处理导航逻辑
function handleNavigation(to, from, next, isLogin) {
  // 对于需要登录验证的部分
  if (to.meta.requiresAuth) {
    if (isLogin) {
      console.log(`成功: 从 ${from.fullPath} 导航到 ${to.fullPath}`);
      next(); // 继续导航
    } else {
      console.log(`失败: 从 ${from.fullPath} 导航到 ${to.fullPath}`);
      ElNotification({
        message: '请先登录！',
        type: 'warning',
      });
      next('/'); // 跳转到登录页
    }
  } else { // 不需要验证的部分
    if (isLogin && to.fullPath === '/') {
      console.log(`成功: 从 ${from.fullPath} 导航到 /home`);
      next('/home'); // 已登录用户跳转到主页
    } else {
      console.log(`成功: 从 ${from.fullPath} 导航到 ${to.fullPath}`);
      next(); // 继续导航
    }
  }
}
export default router
